
package com.be.beadmin.material.impl;

import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaQueryBuilderNew;
import com.be.beadmin.common.utils.JpaSortBuilder;
import com.be.beadmin.material.dto.input.PurchaseOrderDto;
import com.be.beadmin.material.dto.output.PurchaseOrderEx;
import com.be.beadmin.material.entity.*;
import com.be.beadmin.material.mapper.PurchaseOrderDetailMapperEx;
import com.be.beadmin.material.mapper.PurchaseOrderMapper;
import com.be.beadmin.material.mapper.PurchaseOrderMapperEx;
import com.be.beadmin.material.repository.PurchaseOrderDetailRepository;
import com.be.beadmin.material.repository.PurchaseOrderRepository;
import com.be.beadmin.material.service.PurchaseOrderService;
import com.be.beadmin.project.entity.Info;
import com.be.beadmin.project.entity.MasterPlan;
import com.be.beadmin.project.entity.PlanStage;
import com.be.beadmin.project.repository.*;
import com.be.beadmin.project.service.InfoService;
import com.be.beadmin.project.service.MasterPlanService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Order;
import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.function.Function;

/**
* @description 服务实现
* @author zmy
* @date 2023-05-14
**/
@Service
@RequiredArgsConstructor
public class PurchaseOrderServiceImpl implements PurchaseOrderService {

    @Autowired
    private PurchaseOrderRepository purchaseOrderRepository;
    @Autowired
    private PurchaseOrderDetailRepository purchaseOrderDetailRepository;
    @Autowired
    private PurchaseOrderMapper purchaseOrderMapper;

    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private PurchaseOrderDetailMapperEx purchaseOrderDetailExMapper;
    @Autowired
    private PurchaseOrderMapperEx purchaseOrderExMapper;

    @Autowired
    private BatchPlanRepository batchPlanRepository;


    @Autowired
    private MasterPlanService masterPlanService;
    private final PlanStageRepository planStageRepository;

    @Override
    public Page<PurchaseOrderEx> getPurchaseOrderByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<PurchaseOrder> page = purchaseOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilderNew.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(PurchaseOrder_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(PurchaseOrder_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<PurchaseOrderEx> page1 = page.map(purchaseOrderExMapper::toEntity);
            return page1;

    }

    @Override
    public Page<Object> getPurchaseOrderByPage2(PageEntity pageEntity) {

        Page<PurchaseOrderEx> page = purchaseOrderService.getPurchaseOrderByPage(pageEntity);
        Page<Object> map = page.map(new Function<PurchaseOrderEx, Object>() {

            @Override
            public Object apply(PurchaseOrderEx purchaseOrderEx) {
//                String infoId = purchaseOrderEx.getInfoId();
//                MasterPlan masterPlanByInfoIdAndDelete = batchPlanRepository.findBa
//                planStageRepository.fin


                return null;
            }


        });
        return map;
    }

    @Override
    public void addPurchaseOrder(PurchaseOrderDto purchaseOrderDto) {
            PurchaseOrder result = purchaseOrderRepository.findPurchaseOrderByIdAndDelete(purchaseOrderDto.getId(), 0);
            if(ObjectUtil.isNotEmpty(result)) {
                throw new BeadminException("PurchaseOrder不存在,请重新查询");
            }
            PurchaseOrder purchaseOrder = purchaseOrderMapper.toEntity(purchaseOrderDto);
            //开工日期=到货日期+1
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(purchaseOrder.getDeliveryDate());
            calendar.add(calendar.DATE, 1);
            purchaseOrder.setKickoffDate(calendar.getTime());

            purchaseOrderRepository.save(purchaseOrder);
    }

    @Override
    public void updatePurchaseOrder(PurchaseOrderDto purchaseOrderDto) {
            PurchaseOrder purchaseOrder = purchaseOrderRepository.findPurchaseOrderById(purchaseOrderDto.getId());
            purchaseOrder = purchaseOrderMapper.toEntity(purchaseOrderDto);
            purchaseOrderRepository.save(purchaseOrder);
    }


    @Override
    public void delPurchaseOrder(String id) {
        PurchaseOrder purchaseOrder = purchaseOrderRepository.findPurchaseOrderById(id);
        purchaseOrder.setDelete(1);
        purchaseOrderRepository.save(purchaseOrder);
    }

    @Override
    public void delPurchaseOrders (List<String> ids) { }

    @Override
    public Page<Object> getPurchaseOrderDetailByPoId(PageEntity pageEntity, String purchaseOrderId, int type){
        PurchaseOrder purchaseOrderById = purchaseOrderRepository.findPurchaseOrderById(purchaseOrderId);
        Pageable pageable = PageRequest.of(
                pageEntity.getCurrent() -1,
                pageEntity.getPageSize());
        Page<PurchaseOrderDetail> page = purchaseOrderDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(PurchaseOrderDetail_.delete), 0); //过滤为0
                    list.add(pre2);
                    //过滤其他订单的物料信息
                    Predicate pre3 = criteriaBuilder.notEqual(root.get(PurchaseOrderDetail_.PO_IDENTIFICATION), purchaseOrderById.getPo());
                    list.add(pre3);
                    if(type==1){
                        //如果某种物料已经分配完成，则不显示
                        Predicate pre4 = criteriaBuilder.equal(root.get(PurchaseOrderDetail_.IS_FINISHED), "N");
                        list.add(pre4);
                    } else if (type==2) {
                        //如果某种物料已经分配完成，则不显示
                        Predicate pre4 = criteriaBuilder.equal(root.get(PurchaseOrderDetail_.IS_FINISHED), "Y");
                        list.add(pre4);
                    }


                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(PurchaseOrderDetail_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                }
                , pageable);
        Page<Object> page1 = page.map(purchaseOrderDetailExMapper::toEntity);
        return page1;
    }

    public void getPurchaseOrderData(ArrayList<PurchaseOrderTotal> purchaseOrderTotal){
        int len = purchaseOrderTotal.size();
        for (int i = 0; i < len; i++) {

        }




    }
}